package cn.com.headfree.workflow.workflowinfo.controller;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.rowset.serial.SerialException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.gta.edu.sdk.base.controller.BaseController;
import com.gta.edu.sdk.common.constant.Constant;
import com.gta.edu.sdk.common.dto.LoginUserInfo;
import com.gta.edu.sdk.common.dto.Page;
import com.gta.edu.sdk.common.dto.ResultData;
import com.gta.edu.sdk.common.dto.Sort;
import com.gta.edu.sdk.config.DateJsonValueProcessor;
import com.gta.edu.sdk.config.DateMorpher;
import com.gta.edu.sdk.util.CommUtil;
import com.gta.edu.sdk.util.StringUtil;

import cn.com.headfree.call.IFrontFrameServiceCall;
import cn.com.headfree.workflow.dto.WorkFlowNodeStatus;
import cn.com.headfree.workflow.workflowapprove.service.IWorkFlowApproveService;
import cn.com.headfree.workflow.workflowinfo.dto.RoleInfoDto;
import cn.com.headfree.workflow.workflowinfo.model.TWorkFlowInfo;
import cn.com.headfree.workflow.workflowinfo.service.IWorkFlowInfoService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.JSONUtils;

@CrossOrigin("*")
@RestController
@RequestMapping(value = "/workflow/workflowinfo", produces = "application/json;charset=UTF-8")
public class WorkFlowInfoController extends BaseController{
	private static final Logger log = LogManager.getLogger(WorkFlowInfoController.class);
	@Autowired
	private IWorkFlowInfoService workFlowInfoService;
	@Autowired
	private IWorkFlowApproveService workFlowApproveService;
	
	@Autowired
	private IFrontFrameServiceCall frontFrameServiceCall;
	/**
	 * @description 获得工作流信息
	 * @author fengya
	 * @date 2015-8-6 上午11:44:09
	 * @param workFlowId
	 * @return
	 * @return String
	 * @throws SQLException 
	 */
	@RequestMapping(value = "/workFlowById/{workFlowId}", method = RequestMethod.GET)
	public ResultData workFlowById(@PathVariable("workFlowId") String workFlowId) {
		ResultData result = new ResultData();
		try {
			if (!StringUtil.isNullOrEmpty(workFlowId)) {
				TWorkFlowInfo workFlowInfo = this.workFlowInfoService.get(TWorkFlowInfo.class, workFlowId);
				result.setData(workFlowInfo);
//				if(workFlowInfo.getWorkFlowCode() != null){
//					workFlowInfo.setWorkFlowCode(workFlowInfo.getWorkFlowCode());
//				}
			}
		} catch (Exception e) {
			String errorMsg = "根据工作流ID获取工作流信息出现了异常!";
			log.error(errorMsg,e);
			result.setSuccess(false);
			result.setErrorMsg(errorMsg);
		}
		return result;
	}
	
	/**
	 * @description 获得工作流信息
	 * @author fengya
	 * @date 2015-8-6 上午11:44:09
	 * @param workFlowId
	 * @return
	 * @return String
	 * @throws SQLException 
	 */
	@RequestMapping(value = "/findWorkFlowByBusinessId/{businessId}", method = RequestMethod.GET)
	public ResultData findWorkFlowByBusinessId(@PathVariable("businessId") String businessId) {
		ResultData result = new ResultData();
		try {
			if (!StringUtil.isNullOrEmpty(businessId)) {
				TWorkFlowInfo workFlowInfo = this.workFlowInfoService.get(TWorkFlowInfo.class, businessId);
				result.setData(workFlowInfo);
			}
		} catch (Exception e) {
			String errorMsg = "根据工作流ID获取工作流信息出现了异常!";
			log.error(errorMsg,e);
			result.setSuccess(false);
			result.setErrorMsg(errorMsg);
		}
		return result;
	}

	/**
	 * @description 获得工作流信息
	 * @author fengya
	 * @date 2015-8-6 上午11:44:09
	 * @param workFlow
	 * @return
	 * @return String
	 * @throws SQLException 
	 * @throws SerialException 
	 */
	@RequestMapping("/save")
	public JSONObject save(TWorkFlowInfo workFlowInfo) {
		LoginUserInfo userInfo = this.getLongUserInfo();
//		LogType type = LogType.UPDATE;
		Map<String,String> jsonData = new HashMap<String,String>();
		if (workFlowInfo != null) {
			if (StringUtil.isNullOrEmpty(workFlowInfo.getId())) {
				workFlowInfo.setId(null);
				workFlowInfo.setCreater(userInfo.getIscUserId());
				workFlowInfo.setCreateName(userInfo.getIscAdCode());
				workFlowInfo.setCreateTime(new Date());
			}
			workFlowInfo.setUpdater(userInfo.getIscUserId());
			workFlowInfo.setUpdateName(userInfo.getIscAdCode());
			workFlowInfo.setUpdateTime(new Date());
			if (StringUtil.isNullOrEmpty(workFlowInfo.getId())) {
				this.workFlowInfoService.save(workFlowInfo);
			} else {
				TWorkFlowInfo temp = this.workFlowInfoService.get(TWorkFlowInfo.class, workFlowInfo.getId());
				temp.setUpdater(workFlowInfo.getUpdater());
				temp.setUpdateName(workFlowInfo.getUpdateName());
				temp.setUpdateTime(workFlowInfo.getUpdateTime());
				temp.setWorkFlowCode(workFlowInfo.getWorkFlowCode());
				temp.setWorkFlowName(workFlowInfo.getWorkFlowName());
				this.workFlowInfoService.update(temp);
			}
			jsonData.put("result", "success");
			jsonData.put("data", workFlowInfo.getId());
		} else {
			jsonData.put("result", "failure");
		}
		return JSONObject.fromObject(jsonData);
	}
	
	/**
	 * @description 移除流程记录
	 * @author fengya
	 * @date 2015-8-6 下午05:49:32
	 * @param deleteIds
	 * @return
	 * @throws Exception
	 * @return String
	 */
	@RequestMapping("/remove")
	public ResultData remove(String deleteIds) throws Exception {
		ResultData result = new ResultData();
		try { 
			this.workFlowInfoService.removeData(deleteIds);
			result.setData(Constant.DEL_SUCCESS);
		} catch(Exception e) {
			result.setSuccess(false);
			result.setData(Constant.DEL_UN_SUCCESS);
		}
		return result;
	}

	/**
	 * @方法名：list
	 * @功能说明：得到业务类型下流程信息列表
	 * @author fengya
	 * @date 2014-8-7 上午10:38:17
	 * @return void
	 */
	@RequestMapping("/list")
	public JSONObject list(Page<TWorkFlowInfo> page, TWorkFlowInfo workFlowInfo, Sort sort) {
		this.workFlowInfoService.find(page, sort, workFlowInfo);
		return CommUtil.getPageJSONData(page, true);
	}
	
	/**
	 * @方法名：findWorkFlowBySysCode
	 * @功能说明：得到业务类型下流程信息列表
	 * @author fengya
	 * @date 2014-8-7 上午10:38:17
	 * @return void
	 */
	@RequestMapping(value = "/findWorkFlowsBySysCode/{sysCode}", method = RequestMethod.GET)
	public ResultData findWorkFlowsBySysCode(@PathVariable("sysCode") String sysCode) {
		ResultData result = new ResultData();
		try {
			List<TWorkFlowInfo> flowList = this.workFlowInfoService.findWorkFlowsBySysCode(sysCode);
			result.setData(flowList);
		} catch(Exception e) {
			String errorMsg = "根据系统编码获取工作流列表出现了异常！";
			log.error(errorMsg,e);
			result.setSuccess(false);
			result.setErrorMsg(errorMsg);
		}
		return result;
	}
	
	/**
	 * @方法名：list
	 * @功能说明：得到业务类型下流程信息列表
	 * @author fengya
	 * @date 2014-8-7 上午10:38:17
	 * @return void
	 */
	@SuppressWarnings({ "deprecation", "unchecked" })
	@RequestMapping("/findRoles")
	public JSONObject findRoles(Page<RoleInfoDto> page) {
		ResultData result = this.frontFrameServiceCall.findLabelByDomainId(page.getPageSize(),page.getPageNo());
		JSONObject resultData = JSONObject.fromObject(result.getData());
		page.setTotalCount(resultData.getInt("total_number"));
		JsonConfig config = new JsonConfig();
		config.setRootClass(RoleInfoDto.class);
		JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher("yyyy-MM-dd HH:mm:ss"));
		List<RoleInfoDto> list = JSONArray.toList(resultData.getJSONArray("data"), config);
		page.setResult(list);
		return CommUtil.getPageJSONData(page, true);
	}
	
	/**
	 * @description 根据业务和工作流,获得该业务审批的情况记录
	 * @author fengya
	 * @date 2015-9-10 上午10:54:48
	 * @param workFlowId
	 * @param businessId
	 * @return
	 * @return JSONObject
	 * @throws SQLException 
	 */
	@RequestMapping("/showWorkFlowInfo")
	public JSONObject showWorkFlowInfo(String workFlowId,String businessId) {
		TWorkFlowInfo wfi = this.workFlowInfoService.get(TWorkFlowInfo.class, workFlowId);
		JSONObject jsonObject = new JSONObject();
		if (wfi == null) {
			jsonObject.put("result", "failure");
		} else {
			if(wfi.getWorkFlowCode() != null){
				WorkFlowNodeStatus approveNodes = this.workFlowApproveService.findWorkFlowNodes(wfi.getId(), businessId,wfi.getWorkFlowCode());
				DateJsonValueProcessor processor = new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss");
				JsonConfig config = new JsonConfig();
				config.registerJsonValueProcessor(Date.class, processor);
				jsonObject.put("result", "success");
				// 对流程代码中的线条设置他的marked，代表审批线路
				jsonObject.put("code", approveNodes.getWorkFlowJSONObject());
				jsonObject.put("data", JSONObject.fromObject(wfi,config));
				jsonObject.put("approveNodes", JSONObject.fromObject(approveNodes, config));
			}
		}
		return jsonObject;
	}
}
